import { BaseEditor } from './BaseEditor'
import { CellValue, ValidationResult } from '../types'

export class TextEditor extends BaseEditor {
  protected input: HTMLInputElement | null = null
  
  protected createElement(value: CellValue): HTMLElement {
    const editOptions = this.getEditOptions()
    const type = this.column.editType || 'text'
    
    // 创建输入框
    this.input = document.createElement('input')
    
    // 设置输入类型
    switch (type) {
      case 'email':
        this.input.type = 'email'
        break
      case 'url':
        this.input.type = 'url'
        break
      case 'text':
      default:
        this.input.type = 'text'
        break
    }
    
    // 设置属性
    if (editOptions.placeholder) {
      this.input.placeholder = editOptions.placeholder
    }
    
    if (editOptions.required) {
      this.input.required = true
    }
    
    if (editOptions.readonly) {
      this.input.readOnly = true
    }
    
    if (editOptions.maxLength) {
      this.input.maxLength = editOptions.maxLength
    }
    
    if (editOptions.pattern) {
      this.input.pattern = editOptions.pattern
    }
    
    // 设置初始值
    this.setValue(value)
    
    return this.input
  }
  
  getValue(): CellValue {
    if (!this.input) return null
    return this.input.value || null
  }
  
  setValue(value: CellValue): void {
    if (!this.input) return
    this.input.value = value != null ? String(value) : ''
  }
  
  protected customValidate(value: CellValue): ValidationResult {
    if (value == null || value === '') {
      return { valid: true }
    }
    
    const editOptions = this.getEditOptions()
    const strValue = String(value)
    
    // 验证最小长度
    if (editOptions.minLength && strValue.length < editOptions.minLength) {
      return { 
        valid: false, 
        message: `长度不能少于 ${editOptions.minLength} 个字符` 
      }
    }
    
    // 验证最大长度
    if (editOptions.maxLength && strValue.length > editOptions.maxLength) {
      return { 
        valid: false, 
        message: `长度不能超过 ${editOptions.maxLength} 个字符` 
      }
    }
    
    // 验证正则表达式
    if (editOptions.pattern) {
      const regex = new RegExp(editOptions.pattern)
      if (!regex.test(strValue)) {
        return { 
          valid: false, 
          message: '格式不正确' 
        }
      }
    }
    
    // 验证邮箱格式
    if (this.column.editType === 'email') {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
      if (!emailRegex.test(strValue)) {
        return { 
          valid: false, 
          message: '邮箱格式不正确' 
        }
      }
    }
    
    // 验证URL格式
    if (this.column.editType === 'url') {
      try {
        new URL(strValue)
      } catch {
        return { 
          valid: false, 
          message: 'URL格式不正确' 
        }
      }
    }
    
    return { valid: true }
  }
} 